<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>核算地区调节服务占比可视化</title>
    <script src="../js/chart.js"></script>
    <script src="../js/xlsx.full.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            text-align: center;
            margin-top: 50px;
        }
        #chartContainer {
            width: 600px;
            margin: 0 auto;
        }
        select {
            margin-bottom: 20px;
        }
        table {
            width: 80%;
            margin: 20px auto;
            border-collapse: collapse;
            text-align: center;
        }
        th, td {
            border: 1px solid #ddd;
            padding: 8px;
        }
        th {
            background-color: #f2f2f2;
        }
        nav {
            margin-bottom: 20px;
        }
        nav a {
            margin: 0 10px;
            text-decoration: none;
            color: #007BFF;
            font-weight: bold;
        }
        nav a:hover {
            text-decoration: underline;
        }
    </style>
</head>
<body>
    <nav>        <a href="../index.html">首页</a>
        <a href="calculate_service_percentage.html">计算调节服务占比</a>
        <a href="pie_service_percentage.html">核算地区调节服务占比可视化</a>
        <a href="single_service.html">单项调节各地区占比</a>
        <a href="adjust_service_value.html">调整气候调节服务项的价值量</a>
        <a href="multi_service.html">多项调节服务可视化</a>
    </nav>
    <h1>调节服务占比可视化</h1>
    <input type="file" id="fileInput" accept=".xlsx, .xls">
    <select id="regionSelect">
        <option value="">请选择地区</option>
    </select>
    <div id="chartContainer">
        <canvas id="regulationServiceChart"></canvas>
    </div>
    <table id="dataTable">
        <thead>
            <tr>
                <th>行政区划代码</th>
                <th>核算地区</th>
                <th>面积（km²）</th>
                <th>调节服务项</th>
                <th>生态系统</th>
                <th>实物量总值（t）</th>
                <th>价格（元/t）</th>
                <th>价值量总值（元）</th>
                <th>调节服务项占比（%）</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>

    <script>
        let chartInstance = null; // 用于存储当前的图表实例

        document.getElementById('fileInput').addEventListener('change', function(event) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const data = e.target.result;
                    const workbook = XLSX.read(data, {type: 'binary'});
                    const sheetName = workbook.SheetNames[0];
                    const worksheet = workbook.Sheets[sheetName];
                    const jsonData = XLSX.utils.sheet_to_json(worksheet, {header: 1});

                    // Extract headers
                    const headers = jsonData[0];
                    const regionIndex = headers.indexOf('核算地区');
                    const serviceIndex = headers.indexOf('调节服务项');
                    const valueIndex = headers.indexOf('价值量总值（元）');

                    // Extract unique regions
                    const regions = Array.from(new Set(jsonData.slice(1).map(row => row[regionIndex])));

                    // Populate the region select box
                    const regionSelect = document.getElementById('regionSelect');
                    regionSelect.innerHTML = '<option value="">请选择地区</option>';
                    regions.forEach(region => {
                        const option = document.createElement('option');
                        option.value = region;
                        option.textContent = region;
                        regionSelect.appendChild(option);
                    });

                    // Function to draw the pie chart and update the table
                    function drawChart(selectedRegion) {
                        // Filter data for the selected region
                        const filteredData = jsonData.slice(1).filter(row => row[regionIndex] === selectedRegion);

                        // Calculate the total value for each service
                        const serviceValues = {};
                        filteredData.forEach(row => {
                            const service = row[serviceIndex];
                            const value = parseFloat(row[valueIndex]);
                            if (!isNaN(value)) {
                                serviceValues[service] = (serviceValues[service] || 0) + value;
                            }
                        });

                        // Calculate the total value for all services
                        const totalValue = Object.values(serviceValues).reduce((a, b) => a + b, 0);

                        // Calculate the percentage for each service
                        const servicePercentages = Object.keys(serviceValues).map(service => ({
                            label: service,
                            value: (serviceValues[service] / totalValue) * 100
                        }));

                        // Destroy the previous chart instance if it exists
                        if (chartInstance) {
                            chartInstance.destroy();
                        }

                        // Draw the pie chart
                        const ctx = document.getElementById('regulationServiceChart').getContext('2d');
                        chartInstance = new Chart(ctx, {
                            type: 'pie',
                            data: {
                                labels: servicePercentages.map(item => item.label),
                                datasets: [{
                                    data: servicePercentages.map(item => item.value),
                                    backgroundColor: [
                                        '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF', '#FF9F40'
                                    ]
                                }]
                            },
                            options: {
                                responsive: true,
                                plugins: {
                                    title: {
                                        display: true,
                                        text: `调节服务占比 - ${selectedRegion}`
                                    }
                                }
                            }
                        });

                        // Update the table
                        updateTable(filteredData, serviceValues, totalValue);
                    }

                    // Function to update the table
                    function updateTable(data, serviceValues, totalValue) {
                        const tableBody = document.getElementById('dataTable').getElementsByTagName('tbody')[0];
                        tableBody.innerHTML = '';

                        data.forEach(row => {
                            const tr = document.createElement('tr');
                            headers.forEach((header, index) => {
                                const td = document.createElement('td');
                                td.textContent = row[index];
                                tr.appendChild(td);
                            });

                            const service = row[serviceIndex];
                            const value = parseFloat(row[valueIndex]);
                            const percentage = (value / totalValue*100).toFixed(2);
                            const td = document.createElement('td');
                            td.textContent = percentage;
                            tr.appendChild(td);

                            tableBody.appendChild(tr);
                        });
                    }

                    // Event listener for region selection
                    regionSelect.addEventListener('change', function() {
                        const selectedRegion = regionSelect.value;
                        if (selectedRegion) {
                            drawChart(selectedRegion);
                        } else {
                            // Clear the canvas and table if no region is selected
                            const ctx = document.getElementById('regulationServiceChart').getContext('2d');
                            ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
                            document.getElementById('dataTable').getElementsByTagName('tbody')[0].innerHTML = '';
                        }
                    });
                };
                reader.readAsBinaryString(file);
            }
        });
    </script>
</body>
</html>